<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            position: absolute;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <p>
        <button class="left">left</button>
        <button class="right">right</button>
    </p>
    <p class="box"></p>

    <script>
        // 获取元素测试动画函数
        const box = document.querySelector('.box');
        const left = document.querySelector('.left');
        const right = document.querySelector('.right');
        right.addEventListener('click', function () {
            animate(box, 500);
        });
        left.addEventListener('click', function () {
            animate(box, 0);
        });

        // 动画函数封装
        function animate(obj, target, callback) {
            // 清除定时器
            clearInterval(obj.timer);
            // 设置定时器
            obj.timer = setInterval(function () {
                // 步进值（先快后慢）
                let step = (target - obj.offsetLeft) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                if (obj.offsetLeft == target) {
                    clearInterval(obj.timer);
                    callback && callback();
                }
                obj.style.left = obj.offsetLeft + step + 'px';
            }, 15);
        }
    </script>
</body>

</html>